package com.gc.handler;

import com.gc.common.RpcRequest;
import com.gc.service.UserServiceImpl;
import com.gc.util.SpringContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       /* // 如何符合约定，则调用本地方法，返回数据
        if (msg.toString().startsWith("UserService")) {
            String result = new UserServiceImpl()
                    .sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        }*/

        /**
         * 1. 从RpcRequest对象中获取属性
         */
        RpcRequest rpcRequest = (RpcRequest) msg;
        //类名
        String className = rpcRequest.getClassName();
        //方法名
        String methodName = rpcRequest.getMethodName();
        //参数类型
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        //方法参数
        Object[] parameters = rpcRequest.getParameters();

        Class<?> aClass = Class.forName(className);
        //从容器中获取该类对象
        UserServiceImpl userService = (UserServiceImpl) SpringContextUtil.getBean(aClass);

        //反射调用方法
        Method method = aClass.getMethod(methodName, parameterTypes);
        String  result = (String) method.invoke(userService, parameters);

        ctx.writeAndFlush(result);


    }
}
